package com.spshiro.config;

import at.pollux.thymeleaf.shiro.dialect.ShiroDialect;
import org.apache.shiro.spring.web.ShiroFilterFactoryBean;
import org.apache.shiro.web.mgt.DefaultWebSecurityManager;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import java.util.HashMap;
import java.util.LinkedHashMap;
import java.util.Map;

/**
 * @create 2022-03-2022/3/16-21:16
 */
@Configuration
public class ShiroConfig  {


    //创建Realm对象
    @Bean("realm")
    public  UserRealm userRealm(){
        return new UserRealm();
    }

    //DefaultWebSecurityManager 创建
    //指定realm
    @Bean("defaultSM")
    public DefaultWebSecurityManager getDefaultWebSecurityManager(@Qualifier("realm") UserRealm userRealm){
        DefaultWebSecurityManager securityManager =new DefaultWebSecurityManager();

        //关联Realm
        securityManager.setRealm(userRealm);

        return securityManager;
    }

    //创建ShiroFilterFactoryBean
    @Bean
    public ShiroFilterFactoryBean shiroFilterFactoryBean(@Qualifier("defaultSM") DefaultWebSecurityManager defaultWebSecurityManager){
        ShiroFilterFactoryBean shiroFilterFactoryBean =new ShiroFilterFactoryBean();

        //设置安全管理器，关联DefaultWebSecurityManager
        shiroFilterFactoryBean.setSecurityManager(defaultWebSecurityManager);


        //添加过滤器
        //anon：无需认证；authc：认证了才能用；user：必须有’记住我‘才能用；perms：拥有对某个资源的权限
        //roles: 拥有用户
        Map<String,String> shiroFiltermap =new LinkedHashMap<>();

        //加权限 perms[字段]满足才能访问
        shiroFiltermap.put("/user/addUser","perms[u:root]");
        shiroFiltermap.put("/user/updateUser","perms[u:guest]");

        //加限制登陆，登陆了才能访问
        //shiroFiltermap.put("/user/addUser","anon");
        //shiroFiltermap.put("/user/updateUser","authc");
        shiroFiltermap.put("/user/*","authc");

        shiroFilterFactoryBean.setFilterChainDefinitionMap(shiroFiltermap);
        //没有登陆，无权限，自动跳转login页面
        shiroFilterFactoryBean.setLoginUrl("/toLogin");
        //未授权设置跳转
        shiroFilterFactoryBean.setUnauthorizedUrl("/unauthentic");

        return shiroFilterFactoryBean;
    }



    //整合thymeleaf包 ShiroDialect
    @Bean
    public ShiroDialect getShiroDialect(){
        return  new ShiroDialect();
    }

}
